package net.droiding.net;

import java.util.ArrayList;
import java.util.List;

import net.droiding.data.DroidingParser;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class DroidingConnection {

	private static final String BASE_URL = "http://192.168.64.200:8080/droiding_srv/client/droiding";
	private static final String PARAM_ACTION = "action";

	private static final String PARAM_USERNAME = "username";
	private static final String PARAM_PASSWD = "passwd";
	private static final String PARAM_PROVIDERKEY = "provider_key";
	private static final String PARAM_LASTUPDATE = "last_update";

	private static final String ACTION_LOGIN = "login";
	private static final String ACTION_LISTPROVIDERS = "list_providers";
	private static final String ACTION_REFRESHPROVIDERS = "refresh_providers";
	private static final String ACTION_LISTSTATIONS = "list_stations";
	private static final String ACTION_REFRESHSTATIONS = "refresh_stations";
	private static final String ACTION_GETSTATIONDATA = "get_station_data";


	private static HttpClient client = new DefaultHttpClient();


	public static byte[] login(String username, String passwd) throws Exception {
		HttpPost post = new HttpPost(BASE_URL);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair(PARAM_ACTION, ACTION_LOGIN));
		nameValuePairs
				.add(new BasicNameValuePair(PARAM_USERNAME, username));
		nameValuePairs.add(new BasicNameValuePair(PARAM_PASSWD, passwd));

		post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		HttpResponse resp = null;
		try {
			resp = client.execute(post);
			HttpEntity entity = resp.getEntity();
			if (entity != null) {
				byte[] xml = EntityUtils.toByteArray(entity);
				return xml;
			}
		} finally {
			if (post != null)
				post.abort();
		}
		return null;
	}

	public static byte[] getAllProviders(String username, String passwd) throws Exception {
		HttpPost post = new HttpPost(BASE_URL);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair(PARAM_ACTION,
				ACTION_LISTPROVIDERS));
		nameValuePairs
				.add(new BasicNameValuePair(PARAM_USERNAME, username));
		nameValuePairs.add(new BasicNameValuePair(PARAM_PASSWD, passwd));
		post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		HttpResponse resp = null;
		try {
			resp = client.execute(post);
			HttpEntity entity = resp.getEntity();
			if (entity != null) {
				byte[] xml = EntityUtils.toByteArray(entity);
				return xml;
			}
		} finally {
			if (post != null)
				post.abort();
		}
		return null;
	}
	public static byte[] getStationsByProvider(String username, String passwd, String pkey) throws Exception {
		HttpPost post = new HttpPost(BASE_URL);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair(PARAM_ACTION,
				ACTION_LISTSTATIONS));
		nameValuePairs.add(new BasicNameValuePair(PARAM_USERNAME,
				username));
		nameValuePairs
				.add(new BasicNameValuePair(PARAM_PASSWD, passwd));
		nameValuePairs.add(new BasicNameValuePair(PARAM_PROVIDERKEY,
				pkey));
		
		post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		HttpResponse resp = null;
		try {
			resp = client.execute(post);
			HttpEntity entity = resp.getEntity();
			if (entity != null) {
				byte[] xml = EntityUtils.toByteArray(entity);
				return xml;
			}
		} finally {
			if (post != null)
				post.abort();
		}
		return null;
	}
//	public void asyncLogin(Handler handler) {
//		LoginThread thread = new LoginThread(this.username, this.passwd,
//				handler);
//		thread.start();
//	}
//
//	public void asyncGetAllProviders(Handler handler) {
//		GetAllProvidersThread thread = new GetAllProvidersThread(this.username,
//				this.passwd, handler);
//		thread.start();
//	}
//
//	public void asyncGetStations(String pkey, Handler handler) {
//		GetAllStationsThread thread = new GetAllStationsThread(this.username,
//				this.passwd, pkey, handler);
//		thread.start();
//	}

//	public List<Provider> refreshProviders(long lastupdate) {
//		return null;
//	}
//
//	public List<Station> getAllStations(String pkey) {
//		return null;
//	}
//
//	public List<Station> refreshStations(long lastupdate) {
//		return null;
//	}
//
//	public Station getStationData(int id) {
//		return null;
//	}
//
//	public String getUsername() {
//		return username;
//	}
//
//	public void setUsername(String username) {
//		this.username = username;
//	}
//
//	public String getPasswd() {
//		return passwd;
//	}
//
//	public void setPasswd(String passwd) {
//		this.passwd = passwd;
//	}

	private class GetAllStationsThread extends Thread {
		private Handler handler = null;
		private String username = null;
		private String passwd = null;
		private String pkey = null;

		GetAllStationsThread(String username, String passwd, String pkey,
				Handler handler) {
			this.username = username;
			this.passwd = passwd;
			this.pkey = pkey;
			this.handler = handler;
		}

		public void run() {
			HttpPost post = new HttpPost(BASE_URL);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair(PARAM_ACTION,
					ACTION_LISTSTATIONS));
			nameValuePairs.add(new BasicNameValuePair(PARAM_USERNAME,
					this.username));
			nameValuePairs
					.add(new BasicNameValuePair(PARAM_PASSWD, this.passwd));
			nameValuePairs.add(new BasicNameValuePair(PARAM_PROVIDERKEY,
					this.pkey));
			HttpResponse resp = null;
			try {
				post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				resp = client.execute(post);
				HttpEntity entity = resp.getEntity();
				if (entity != null) {
					byte[] xml = EntityUtils.toByteArray(entity);
					Message msg = handler.obtainMessage();
					Bundle b = new Bundle();
					b.putString("result", "ok");
					b.putByteArray("xml", xml);
					msg.setData(b);
					handler.sendMessage(msg);
					return;
				}
				Message msg = handler.obtainMessage();
				Bundle b = new Bundle();
				b.putString("result", "ko");
				b.putString("error", "null response");
				msg.setData(b);
				handler.sendMessage(msg);
			} catch (Exception e) {
				Message msg = handler.obtainMessage();
				Bundle b = new Bundle();
				b.putString("result", "ko");
				b.putString("error", e.getMessage());
				msg.setData(b);
				handler.sendMessage(msg);
			} finally {
				if (post != null)
					post.abort();
			}
		}
	}

	private class GetAllProvidersThread extends Thread {
		private Handler handler = null;
		private String username = null;
		private String passwd = null;

		GetAllProvidersThread(String username, String passwd, Handler handler) {
			this.username = username;
			this.passwd = passwd;
			this.handler = handler;
		}

		public void run() {
			HttpPost post = new HttpPost(BASE_URL);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair(PARAM_ACTION,
					ACTION_LISTPROVIDERS));
			nameValuePairs.add(new BasicNameValuePair(PARAM_USERNAME,
					this.username));
			nameValuePairs
					.add(new BasicNameValuePair(PARAM_PASSWD, this.passwd));
			HttpResponse resp = null;
			try {
				post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				resp = client.execute(post);
				HttpEntity entity = resp.getEntity();
				if (entity != null) {
					byte[] xml = EntityUtils.toByteArray(entity);
					Message msg = handler.obtainMessage();
					Bundle b = new Bundle();
					b.putString("result", "ok");
					b.putByteArray("xml", xml);
					msg.setData(b);
					handler.sendMessage(msg);
					return;
				}
				Message msg = handler.obtainMessage();
				Bundle b = new Bundle();
				b.putString("result", "ko");
				b.putString("error", "null response");
				msg.setData(b);
				handler.sendMessage(msg);
			} catch (Exception e) {
				Message msg = handler.obtainMessage();
				Bundle b = new Bundle();
				b.putString("result", "ko");
				b.putString("error", e.getMessage());
				msg.setData(b);
				handler.sendMessage(msg);
			} finally {
				if (post != null)
					post.abort();
			}
		}
	}

	private class LoginThread extends Thread {
		private Handler handler = null;
		private String username = null;
		private String passwd = null;

		LoginThread(String username, String passwd, Handler handler) {
			this.username = username;
			this.passwd = passwd;
			this.handler = handler;
		}

		public void run() {
			HttpPost post = new HttpPost(BASE_URL);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair(PARAM_ACTION,
					ACTION_LOGIN));
			nameValuePairs.add(new BasicNameValuePair(PARAM_USERNAME,
					this.username));
			nameValuePairs
					.add(new BasicNameValuePair(PARAM_PASSWD, this.passwd));
			HttpResponse resp = null;
			try {
				post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				resp = client.execute(post);
				HttpEntity entity = resp.getEntity();
				if (entity != null) {
					byte[] xml = EntityUtils.toByteArray(entity);
					if (DroidingParser.parseLogin(xml) != null) {
						Message msg = handler.obtainMessage();
						Bundle b = new Bundle();
						b.putString("result", "ok");
						msg.setData(b);
						handler.sendMessage(msg);
						return;
					}
					Message msg = handler.obtainMessage();
					Bundle b = new Bundle();
					b.putString("result", "ko");
					b.putString("error", "null response");
					msg.setData(b);
					handler.sendMessage(msg);
				}
			} catch (Exception e) {
				Message msg = handler.obtainMessage();
				Bundle b = new Bundle();
				b.putString("result", "ko");
				b.putString("error", e.getMessage());
				msg.setData(b);
				handler.sendMessage(msg);
			} finally {
				if (post != null)
					post.abort();
			}
		}
	}
}
